package com.cy.pj.ajax.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping("/")
public class AjaxController {
    //假设这是数据库中表
    private List<Map<String,Object>> list=new ArrayList<>();
    public AjaxController(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", "100");
        map.put("name", "小米");
        map.put("remark", "不错");
        list.add(map);
    }

    @PutMapping("doAjaxUpdate")
    @ResponseBody
    public String doAjaxUpdate(@RequestParam Map<String,Object> map){
        String id=(String) map.get("id");
        Iterator<Map<String, Object>> it = list.iterator();
        Map<String,Object> obj=null;
        while (it.hasNext()){
            obj=it.next();
            if(obj.get("id").equals(id))break;
        }
        obj.put("name", map.get("name"));
        obj.put("remark", map.get("remark"));
        return "update ok";
    }

    @DeleteMapping("doAjaxDelete/{id}")
    @ResponseBody
    public String doAjaxDelete(@PathVariable Integer id){
        Iterator<Map<String, Object>> it = list.iterator();//获取迭代器
        while (it.hasNext()){//判断是否有数据
            Map<String, Object> map = it.next();//取出数据
            if(map.get("id").equals(String.valueOf(id))){
                it.remove();//用迭代器删除
            }
        }
        return "delete ok";
    }

    @PostMapping("doAjaxPost")
    @ResponseBody
    public String doAjaxPost(@RequestParam Map<String,Object> map){
        list.add(map);
        return "save ok";
    }

//    @CrossOrigin //此注解描述的方法支持跨域访问
    @GetMapping("doAjaxGet")//此注解描述的方法只能处理Get请求
//    @RequestMapping(value = "doAjaxGet",method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String,Object>> doAjaxGet(){
        return list;
    }

    //传统方式-----------------------
    @RequestMapping("doNotAjaxUI")
    public String doNotAjaxUI(){
        return "not-ajax-01";
    }

    @RequestMapping(value = "doNotAjaxStart")
    public String doNotAjaxStart(Model model){
        model.addAttribute("result", "鲈鱼");
        return "not-ajax-01";
    }

    //Ajax方式------------------------
    @RequestMapping("doAjaxStart")
    @ResponseBody
    public String doAjaxStart() throws InterruptedException {
        Thread.sleep(3000);
        return "二狗子来了";
    }

}
